<template>
  <div class="wms-inventory-search">
    <ElCard shadow="never" class="search-card">
      <ElForm
        ref="searchFormRef"
        :model="searchForm"
        :inline="true"
        label-width="80px"
        class="search-form"
      >
        <ElRow :gutter="16">
          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="仓库" prop="warehouseId">
              <ElSelect
                v-model="searchForm.warehouseId"
                placeholder="请选择仓库"
                clearable
                filterable
                style="width: 100%"
                @change="handleWarehouseChange"
              >
                <ElOption
                  v-for="warehouse in warehouseList"
                  :key="warehouse.id"
                  :label="warehouse.warehouseName"
                  :value="warehouse.id"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="库区" prop="areaId">
              <ElSelect
                v-model="searchForm.areaId"
                placeholder="请选择库区"
                clearable
                filterable
                style="width: 100%"
                :disabled="!searchForm.warehouseId"
              >
                <ElOption
                  v-for="area in filteredAreaList"
                  :key="area.id"
                  :label="area.areaName"
                  :value="area.id"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="商品编码" prop="itemCode">
              <ElInput
                v-model="searchForm.itemCode"
                placeholder="请输入商品编码"
                clearable
                @keyup.enter="handleSearch"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="商品名称" prop="itemName">
              <ElInput
                v-model="searchForm.itemName"
                placeholder="请输入商品名称"
                clearable
                @keyup.enter="handleSearch"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="SKU编码" prop="skuCode">
              <ElInput
                v-model="searchForm.skuCode"
                placeholder="请输入SKU编码"
                clearable
                @keyup.enter="handleSearch"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="SKU名称" prop="skuName">
              <ElInput
                v-model="searchForm.skuName"
                placeholder="请输入SKU名称"
                clearable
                @keyup.enter="handleSearch"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="批次号" prop="batchNo">
              <ElInput
                v-model="searchForm.batchNo"
                placeholder="请输入批次号"
                clearable
                @keyup.enter="handleSearch"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="库存状态" prop="stockStatus">
              <ElSelect
                v-model="searchForm.stockStatus"
                placeholder="请选择库存状态"
                clearable
                style="width: 100%"
              >
                <ElOption label="有库存" value="in_stock" />
                <ElOption label="无库存" value="out_of_stock" />
                <ElOption label="低库存" value="low_stock" />
                <ElOption label="已分配" value="allocated" />
              </ElSelect>
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="过期状态" prop="expirationStatus">
              <ElSelect
                v-model="searchForm.expirationStatus"
                placeholder="请选择过期状态"
                clearable
                style="width: 100%"
              >
                <ElOption label="正常" value="normal" />
                <ElOption label="即将过期" value="expiring_soon" />
                <ElOption label="已过期" value="expired" />
              </ElSelect>
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="数量范围" prop="quantityRange">
              <ElInputNumber
                v-model="searchForm.minQuantity"
                placeholder="最小数量"
                :min="0"
                :precision="3"
                style="width: 48%"
              />
              <span style="margin: 0 2%">-</span>
              <ElInputNumber
                v-model="searchForm.maxQuantity"
                placeholder="最大数量"
                :min="0"
                :precision="3"
                style="width: 48%"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="更新时间" prop="updateTimeRange">
              <ElDatePicker
                v-model="searchForm.updateTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem>
              <ElSpace>
                <ElButton type="primary" @click="handleSearch" v-ripple>
                  <ElIcon><Search /></ElIcon>
                  搜索
                </ElButton>
                <ElButton @click="handleReset" v-ripple>
                  <ElIcon><Refresh /></ElIcon>
                  重置
                </ElButton>
                <ElButton
                  type="info"
                  text
                  @click="toggleExpand"
                  v-if="showExpandButton"
                >
                  <ElIcon
                    ><component :is="isExpanded ? ArrowUp : ArrowDown"
                  /></ElIcon>
                  {{ isExpanded ? "收起" : "展开" }}
                </ElButton>
              </ElSpace>
            </ElFormItem>
          </ElCol>
        </ElRow>
      </ElForm>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { useWmsStore } from "@/store/modules/wms";
import { Search, Refresh, ArrowUp, ArrowDown } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";

defineOptions({ name: "WmsInventorySearch" });

// Props
interface Props {
  filter?: WMS.Inventory.InventoryQueryParams;
}

const props = withDefaults(defineProps<Props>(), {
  filter: () => ({}),
});

// Emits
interface Emits {
  (e: "search", params: WMS.Inventory.InventoryQueryParams): void;
  (e: "reset"): void;
  (e: "update:filter", params: WMS.Inventory.InventoryQueryParams): void;
}

const emit = defineEmits<Emits>();

// 状态管理
const wmsStore = useWmsStore();

// 表单引用
const searchFormRef = ref<FormInstance>();

// 搜索表单数据
const searchForm = ref<WMS.Inventory.InventoryQueryParams>({
  warehouseId: undefined,
  areaId: undefined,
  itemCode: "",
  itemName: "",
  skuCode: "",
  skuName: "",
  batchNo: "",
  stockStatus: undefined,
  expirationStatus: undefined,
  minQuantity: undefined,
  maxQuantity: undefined,
  updateTimeRange: undefined,
});

// 展开/收起状态
const isExpanded = ref(false);
const showExpandButton = ref(true);

// 计算属性
const warehouseList = computed(() => {
  return wmsStore.getActiveWarehouses || [];
});

const filteredAreaList = computed(() => {
  if (!searchForm.value.warehouseId) {
    return [];
  }
  return wmsStore.getAreasByWarehouseId(searchForm.value.warehouseId) || [];
});

// 监听props变化
watch(
  () => props.filter,
  (newFilter) => {
    if (newFilter) {
      Object.assign(searchForm.value, newFilter);
    }
  },
  { immediate: true, deep: true },
);

// 监听搜索表单变化
watch(
  searchForm,
  (newForm) => {
    emit("update:filter", { ...newForm });
  },
  { deep: true },
);

// 仓库变化处理
const handleWarehouseChange = () => {
  // 清空库区选择
  searchForm.value.areaId = undefined;
};

// 搜索处理
const handleSearch = () => {
  const params = { ...searchForm.value };

  // 处理时间范围
  if (params.updateTimeRange && params.updateTimeRange.length === 2) {
    params.updateTimeStart = params.updateTimeRange[0];
    params.updateTimeEnd = params.updateTimeRange[1];
    delete params.updateTimeRange;
  }

  // 过滤空值
  Object.keys(params).forEach((key) => {
    if (
      params[key] === "" ||
      params[key] === null ||
      params[key] === undefined
    ) {
      delete params[key];
    }
  });

  emit("search", params);
};

// 重置处理
const handleReset = () => {
  searchFormRef.value?.resetFields();
  searchForm.value = {
    warehouseId: undefined,
    areaId: undefined,
    itemCode: "",
    itemName: "",
    skuCode: "",
    skuName: "",
    batchNo: "",
    stockStatus: undefined,
    expirationStatus: undefined,
    minQuantity: undefined,
    maxQuantity: undefined,
    updateTimeRange: undefined,
  };
  emit("reset");
};

// 展开/收起切换
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value;
};

// 初始化
onMounted(() => {
  // 确保基础数据已加载
  if (wmsStore.warehouseList.length === 0) {
    wmsStore.getWarehouseList();
  }
  if (wmsStore.areaList.length === 0) {
    wmsStore.getAreaList();
  }
});

// 暴露方法
defineExpose({
  handleSearch,
  handleReset,
  searchForm,
});
</script>

<style lang="scss" scoped>
.wms-inventory-search {
  margin-bottom: 16px;

  .search-card {
    :deep(.el-card__body) {
      padding: 16px 20px;
    }
  }

  .search-form {
    :deep(.el-form-item) {
      margin-bottom: 16px;
    }

    :deep(.el-form-item__label) {
      font-weight: 500;
    }
  }
}

// 响应式处理
@media (max-width: 768px) {
  .wms-inventory-search {
    .search-form {
      :deep(.el-form-item) {
        margin-bottom: 12px;
      }
    }
  }
}
</style>
